import { Checkbox, Row, Col, Divider, message, Select, Form } from "antd";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { useModel } from "umi";
import { AllMembers, FindOneRole } from "../../_graphql/approles";
import { Button } from "@douyinfe/semi-ui";

const layout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
const tailLayout = { wrapperCol: { offset: 6, span: 16 } };

const SetRoleMembers = ({ application, roleKey, role, roleMembers, reloadData, reloadRole }) => {
    const { graphqlFetch } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const form = Form.useForm();

    const state = useReactive({
        loading: false,
        members: [],
        selectedMembers: [],
        selectedLevel: 1,
    });

    const loadMembers = async () => {
        let res = await graphqlFetch({
            query: AllMembers,
            variables: {},
        });
        state.members = res?.a?.nodes?.filter((item) => roleMembers.findIndex((_item) => _item.omUuid === item.omUuid) === -1) || [];
    };

    useEffect(() => {
        loadMembers();
    }, []);

    const saveRoleMembers = async () => {
        if (!state.selectedLevel) return message.warn("没有选择层级");
        state.loading = true;
        let res = await graphqlFetch({
            query: FindOneRole,
            variables: {
                aiUuid: application.aiUuid,
                arName: roleKey,
            },
        });
        let createOrUpdateRole, createRoleMembers;
        let variables = {
            aiUuid: application.aiUuid,
            arName: roleKey,
            arType: role.type,
            arUpti: new Date().getUTCTime(),
            arLeve: role.level,
            arRemk: role.text,
        };
        let params = "$aiUuid: UUID!, $arName: String!, $arType: String!, $arLeve: Int!, $arRemk: String";
        let neworgRole = {};
        if (res.a) {
            params += ", $arUpti: BigInt!";
            createOrUpdateRole = `updateApplicationInnerRoleByAiUuidAndArName(input: { applicationInnerRolePatch: { arLeve: $arLeve, arRemk: $arRemk, arType: $arType, arUpti: $arUpti }, aiUuid: $aiUuid, arName: $arName }) { clientMutationId }`;
            variables = { ...variables, arUpti: new Date().getUTCTime() };
        } else {
            params += ", $arCrti: BigInt!, $arUpti: BigInt!";
            createOrUpdateRole = `createApplicationInnerRole(input: { applicationInnerRole: { aiUuid: $aiUuid, arName: $arName, arCrti: $arCrti, arUpti: $arUpti, arLeve: $arLeve, arRemk: $arRemk, arType: $arType } }) { clientMutationId }`;
            neworgRole = variables;
            variables = { ...variables, arCrti: new Date().getUTCTime(), arUpti: new Date().getUTCTime() };
        }
        createRoleMembers = state.selectedMembers.map(
            (item, index) => `a${index}: createApplicationInnerRolesMember(input: { applicationInnerRolesMember: {
                arName: "${roleKey}", aiUuid: "${application.aiUuid}", omUuid: "${item}", arLeve: ${state.selectedLevel} } }) { clientMutationId }`
        );
        let query = `mutation MyMutation(${params}) { ${createOrUpdateRole} ${createRoleMembers} }`;
        res = await graphqlFetch({ query, variables });
        if (res) {
            message.success("成功设置应用角色成员信息");
            await reloadData();
            if (neworgRole?.aiUuid) reloadRole(neworgRole);
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    const levels = [];
    if (role.level) for (let i = 1; i <= role.level; i++) levels.push(i);

    return (
        <div style={{ padding: "0 30px" }}>
            <div style={{ marginBottom: 16 }}>
                选择层级：
                <Select defaultValue={state.selectedLevel} style={{ width: 200 }} onChange={(value) => (state.selectedLevel = value)}>
                    {levels.map((item) => (
                        <Select.Option key={item} value={item}>
                            {item + " 级审核人"}
                        </Select.Option>
                    ))}
                </Select>
            </div>

            <div style={{ marginBottom: 16 }}>
                <Checkbox.Group style={{ width: "100%" }} onChange={(checkedValues) => (state.selectedMembers = checkedValues)}>
                    <Row>
                        {state.members.map((item) => (
                            <Col span={6} key={item.omUuid}>
                                <Checkbox value={item.omUuid}>{item.omName}</Checkbox>
                            </Col>
                        ))}
                    </Row>
                </Checkbox.Group>
            </div>

            <Divider />
            <div style={{ textAlign: "center" }}>
                <Button theme="solid" disabled={state.selectedMembers.length === 0} onClick={saveRoleMembers}>
                    保存应用角色成员信息
                </Button>
            </div>
        </div>
    );
};

export default SetRoleMembers;
